package com.find.jwt.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.find.jwt.bean.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtLoginFilter
 * @Description 登录的时候给用户token
 * @Author find me
 * @Date 2020/6/25 0025 17:55
 * @Version 1.0
 */
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {

    // 实现构造方法

    /**
     * @param defaultFilterProcessesUrl
     * @param authenticationManager
     */
    public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(authenticationManager);
    }

    /**
     * 提取用户名和密码去做登录
     *
     * @param req
     * @param httpServletResponse
     * @return
     * @throws AuthenticationException
     * @throws IOException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException {
        // 为了获取登录的数据转换成user

        User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
    }

    // 登录成功的回调 生成jwt
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse resp,
                                            FilterChain chain, Authentication authResult) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();//获取登录用户的角色
        StringBuffer sb = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            //获取当前角色
            sb.append(authority.getAuthority()).append(",");
        }
        // 生成jwt的token
        String jwt = Jwts.builder()
                .claim("authorities", sb)// 用户的角色
                .setSubject(authResult.getName()) // 主题
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) // 过期时间
                .signWith(SignatureAlgorithm.HS512, "findme") // 签名的算法
                .compact();
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        map.put("msg", "登录成功");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }

    // 登录失败

    /**
     * @param req
     * @param resp
     * @param failed
     * @throws IOException
     * @throws ServletException 登录失败的异常，根据异常判断失败的原因
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp,
                                              AuthenticationException failed) throws IOException, ServletException {
        Map<String, String> map = new HashMap<>();
        map.put("msg", "登录失败");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}
